exports.__esModule = true;

var _jimp = require('jimp');

var _jimp2 = _interopRequireDefault(_jimp);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

class PartsService extends think.Service {
    constructor() {
        super();
        this.partsModel = this.db['cms_parts'];
        this.areaModel = this.db['cms_area'];
        this.cellModel = this.db['cms_cell'];
        this.partsGroupModel = this.db['cms_parts_group'];
        this.eventGroupModel = this.db['cms_event_group'];

        // this.partsModel.belongsTo(this.cellModel, {
        //     foreignKey: 'BGID',
        //     targetKey: 'BGID'
        // })
        this.partsModel.belongsTo(this.partsGroupModel, {
            foreignKey: 'group_code',
            targetKey: 'group_code'
        });
        this.partsModel.belongsTo(this.areaModel, {
            foreignKey: 'area_code',
            targetKey: 'area_code'
        });
    }

    /**
     * 获取区域所有信息
     *
     * @returns
     */
    getAreaData() {
        var _this = this;

        return _asyncToGenerator(function* () {
            const attributes = ['id', 'area_code', 'area_name', 'parent_id', 'parent_ids'];
            try {
                return yield _this.areaModel.findAll({
                    attributes: attributes
                });
            } catch (err) {
                return _this.exceptionService.handleError(err);
            }
        })();
    }
    getPGData() {
        var _this2 = this;

        return _asyncToGenerator(function* () {
            const attributes = ['id', 'group_code', 'group_name', 'parent_id'];
            try {
                return yield _this2.partsGroupModel.findAll({
                    where: {
                        del_flag: 0
                    },
                    attributes: attributes
                });
            } catch (err) {
                return _this2.exceptionService.handleError(err);
            }
        })();
    }

    getEVData() {
        var _this3 = this;

        return _asyncToGenerator(function* () {
            const attributes = ['id', 'group_code', 'group_name', 'parent_id'];
            try {
                return yield _this3.eventGroupModel.findAll({
                    where: {
                        del_flag: 0
                    },
                    attributes: attributes
                });
            } catch (err) {
                return _this3.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 分页获取部件信息
     * @param {Object} data
     */
    getPartsList(data) {
        var _this4 = this;

        return _asyncToGenerator(function* () {
            const OP = _this4.db.Sequelize.Op;
            let where = {};
            let query = {};
            data.start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
            console.log('76', data);
            if (data.user_ids.length > 0) {
                query = {
                    create_by: {
                        [OP.in]: data.user_ids
                    }

                };
            }
            if (data.area_id) {
                where = {
                    [OP.or]: {
                        id: data.area_id,
                        parent_ids: {
                            [OP.like]: '%' + data.parent_ids + data.area_id + '%'
                        }
                    }
                };
            }
            try {
                return yield _this4.partsModel.findAndCountAll({
                    order: [['create_date', 'DESC']],
                    limit: parseInt(data.pageSize),
                    offset: parseInt(data.start),
                    where: query,

                    include: [{
                        model: _this4.partsGroupModel,
                        attributes: ['group_name', 'group_pic_path']

                    }, {
                        model: _this4.areaModel,
                        where: where
                    }]

                });
            } catch (err) {
                return _this4.exceptionService.handleError(err);
            }
        })();
    }

    /**
     * 部件管理获取部件列表
     */
    getPartsLists(data) {
        var _this5 = this;

        return _asyncToGenerator(function* () {
            const start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
            const size = parseInt(data.pageSize);
            const searchArr = [];
            let searchWhere = '';
            if (data.user_ids.length > 0) {
                const ids = [];
                for (const item of data.user_ids) {
                    ids.push(`'${item}'`);
                };
                searchArr.push(`a.create_by in (${ids})`);
            }
            if (data.area_id) {
                searchArr.push(`b.id = ${data.area_id}`);
            }
            if (data.parent_name && data.sub_name) {
                searchArr.push(`a.group_code = ${data.sub_name}`);
            } else {
                searchArr.push(`a.group_code LIKE '${data.parent_name}%'`);
            }
            if (data.start_time && data.end_time) {
                searchArr.push(`a.create_date BETWEEN '${data.start_time}' AND '${data.end_time}'`);
            }
            for (let i = 0; i < searchArr.length; i++) {
                if (i === 0) {
                    searchWhere = ' WHERE ' + searchArr[i];
                } else {
                    searchWhere += ' AND ' + searchArr[i];
                }
            }
            try {
                const sql = `SELECT a.*,b.id AS area_id,b.area_name,b.parent_id,b.parent_ids,b.scope_path,b.city_type,c.group_name,c.group_pic_path
                         FROM cms_parts AS a
                         LEFT JOIN cms_area AS b ON a.area_code = b.area_code
                         LEFT JOIN cms_parts_group AS c ON a.group_code = c.group_code ${searchWhere}
                         ORDER BY a.create_date DESC LIMIT ${start}, ${size}`;

                const sqlCount = `SELECT count(*) AS count
                              FROM cms_parts AS a
                              LEFT JOIN cms_area AS b ON a.area_code = b.area_code
                              LEFT JOIN cms_parts_group AS c ON a.group_code = c.group_code ${searchWhere}`;

                const rows = yield _this5.CrudService.querySql(sql);
                const res = yield _this5.CrudService.querySql(sqlCount);
                const count = res[0].count;

                return {
                    rows,
                    count
                };
            } catch (error) {
                return _this5.exceptionService.handleError(error);
            }
        })();
    }
    /**
     * 保存图片
     * @param {Object} pathObj 图片路径对象
     */
    uploadImg(pathObj) {
        return _asyncToGenerator(function* () {
            const aj = think.ajaxJson();
            let serverIP = 'http://' + think.config('staticIp') + ':' + think.config('port'); // 开发环境
            const isDev = think.env === 'development'; // 是否开发环境，true开发环境
            if (!isDev) {
                // 生产环境
                serverIP = 'http://' + think.config('staticIp') + ':' + think.config('proxyPort');
            }
            if (pathObj) {
                console.log(pathObj);
                try {
                    // const img800 = await Jimp.read(pathObj.filePath);
                    // img800.scaleToFit(800, Jimp.AUTO).write(pathObj.filePath);
                    aj.success = true;
                    aj.msg = '上传成功';
                    aj.result = {
                        fileName: pathObj.fileName,
                        filePathStatic: serverIP + '/' + pathObj.filePathStatic
                    };
                    return aj;
                } catch (error) {
                    aj.success = false;
                    aj.msg = '图片裁切错误' + error;
                    return aj;
                }
            } else {
                aj.success = false;
                aj.msg = '图片保存错误';
                return aj;
            }
        })();
    }

    /**
     * 新增/更改部件
     * @param {Object} data 部件属性
     */
    doAddOrUpdate(userid, data) {
        var _this6 = this;

        return _asyncToGenerator(function* () {
            const aj = think.ajaxJson();
            aj.success = false;
            const AUTORes = yield _this6.CrudService.querySql("SHOW TABLE STATUS WHERE Name='cms_parts'");
            console.log('138138', data);
            if (data) {
                try {
                    // 修改
                    if (data.id != '' && data.id != null) {
                        console.log('无ID');
                        const code = data.area_code + data.group_code;
                        // let code = data.BGID + data.ObjLabelCode;
                        data.ObjID = code + _this6.fix(AUTORes[0].Auto_increment, 6);
                        // data.create_date = think.datetime();
                        data.update_by = userid;
                        data.update_date = think.datetime(new Date().getTime());
                        const Res = yield _this6.partsModel.update(data, {
                            where: {
                                id: data.id
                            }
                        });
                        if (Res) {
                            aj.success = true;
                            aj.msg = '修改成功';
                        } else {
                            aj.msg = '更新操作失败';
                        }
                    } else {
                        console.log('有ID');
                        const code = data.area_code + data.group_code;
                        // 新增
                        data.ObjID = code + _this6.fix(AUTORes[0].Auto_increment, 6);
                        data.create_by = userid;
                        data.create_date = new Date();
                        const Res = yield _this6.partsModel.create(data);
                        if (Res) {
                            aj.success = true;
                            aj.msg = '新增成功';
                        } else {
                            aj.msg = '插入操作失败';
                        }
                    }
                } catch (error) {
                    aj.msg = '数据库查询错误:' + error;
                }
            } else {
                aj.msg = '参数未知';
            }
            return aj;
        })();
    }

    /**
     * 获取部件列表
     * @param {*Object} data
     */
    getPartsList3333(data) {
        var _this7 = this;

        return _asyncToGenerator(function* () {
            const aj = think.ajaxJson();
            aj.success = false;
            data.start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
            const where = {
                create_by: data.userId
            };
            if (data.userId) {
                try {
                    const Res = yield _this7.partsModel.findAndCountAll({
                        where: where,
                        order: [['id', 'DESC']],
                        limit: parseInt(data.pageSize),
                        offset: parseInt(data.start),
                        // include: [{
                        //     model: this.cellModel,
                        //     attributes: ['BGID'],
                        //     include: [{
                        //         model: this.areaModel,
                        //         attributes: ['parent_ids', 'area_name'],
                        //     }]
                        // }]
                        include: [{
                            model: _this7.partsGroupModel,
                            attributes: ['group_name']

                        }, {
                            model: _this7.areaModel
                        }]

                    });
                    if (Res) {
                        for (const item of Res.rows) {
                            if (item.cms_area) {
                                const idArr = item.cms_area.parent_ids.split(',');
                                const areaRes = yield _this7.areaModel.findAll({
                                    where: {
                                        id: idArr
                                    }
                                });
                                const list = [];
                                idArr.map(function (item2) {
                                    areaRes.map(function (item3) {
                                        if (item2 == item3.id) {
                                            list.push(item3.area_name);
                                        }
                                    });
                                });
                                list.push(item.cms_area.area_name);
                                // item.dataValues.cms_area = null
                                item.dataValues.address = list;
                            } else {
                                item.dataValues.address = [];
                            }
                        }
                    }

                    aj.msg = '查询成功';
                    aj.success = true;
                    aj.result = Res;
                } catch (error) {
                    aj.msg = error;
                }
            } else {
                aj.msg = '用户名未知';
            }

            return aj;
        })();
    }

    getPartsAllList(data) {
        var _this8 = this;

        return _asyncToGenerator(function* () {
            const aj = think.ajaxJson();
            aj.success = false;
            // data.start = (parseInt(data.page) - 1) * parseInt(data.pageSize)
            // if (data.userId) {
            try {
                const Res = yield _this8.partsModel.findAll({
                    // where: where,
                    // order: [
                    //     ['id', 'DESC']
                    // ],
                    // attributes: ['id', 'ObjID', 'ObjName', 'ObjState', 'original_x', 'original_y', 'baidu_x', 'baidu_y', 'pic_path', 'address_name'],
                    attributes: ['id', 'baidu_x', 'baidu_y']
                    // limit: parseInt(data.pageSize),
                    // offset: parseInt(data.start),
                    // include: [{
                    //     model: this.cellModel,
                    //     attributes: ['BGID'],
                    //     include: [{
                    //         model: this.areaModel,
                    //         attributes: ['parent_ids', 'area_name'],
                    //     }]
                    // }]
                    // include: [{
                    //     model: this.partsGroupModel,
                    //     attributes: ['group_name'],

                    // }, {
                    //     model: this.areaModel,
                    //     attributes: ['area_name'],
                    // }]

                });
                // if (Res) {
                //     for (let item of Res) {
                //         let imgList = item.pic_path.split(",");
                //         let newImgList = [];
                //         imgList.map(item2 => {
                //             if (item2) {
                //                 newImgList.push('http://' + think.config('staticIp') + ':' + think.config('port') + think.config('imagePath') + '/' + item2)
                //             }
                //         })
                //         item.pic_path = newImgList;
                //         // item.pic_path='123'
                //         // if (item.cms_area) {
                //         //     const idArr = item.cms_area.parent_ids.split(",")
                //         //     const areaRes = await this.areaModel.findAll({
                //         //         where: {
                //         //             id: idArr
                //         //         }
                //         //     })
                //         //     let list = [];
                //         //     idArr.map(item2 => {
                //         //         areaRes.map(item3 => {
                //         //             if (item2 == item3.id) {
                //         //                 list.push(item3.area_name)
                //         //             }
                //         //         })
                //         //     })
                //         //     list.push(item.cms_area.area_name)
                //         //     // item.dataValues.cms_area = null
                //         //     item.dataValues.address = list
                //         // } else {
                //         //     item.dataValues.address = []
                //         // }
                //     }

                // }

                aj.msg = '查询成功';
                aj.success = true;
                aj.result = Res;
            } catch (error) {
                aj.msg = 'error' + error;
            }
            // } else {
            //     aj.msg = "用户名未知"
            // }

            return aj;
        })();
    }
    getPartOneInfo(data) {
        var _this9 = this;

        return _asyncToGenerator(function* () {
            const aj = think.ajaxJson();
            aj.success = false;
            console.log(data);
            const where = {
                id: data.id
            };
            if (data.id) {
                try {
                    const Res = yield _this9.partsModel.findOne({
                        where: where
                    });
                    if (Res) {
                        aj.msg = '查询成功';
                        aj.success = true;
                        aj.result = Res;
                    } else {
                        aj.msg = '当前id不存在';
                        aj.success = false;
                    }
                } catch (error) {
                    aj.msg = error;
                }
            } else {
                aj.msg = '用户名未知';
            }

            return aj;
        })();
    }
    /**
     * 获取部件信息
     * @param {Object} data
     */
    getParts(data) {
        var _this10 = this;

        return _asyncToGenerator(function* () {
            const aj = think.ajaxJson();
            let serverIP = 'http://' + think.config('staticIp') + ':' + think.config('port'); // 开发环境
            const isDev = think.env === 'development'; // 是否开发环境，true开发环境
            if (!isDev) {
                // 生产环境
                serverIP = 'http://' + think.config('staticIp') + ':' + think.config('proxyPort');
            }
            aj.success = false;
            console.log(data);
            const where = {
                id: data.id
            };
            if (data.id) {
                try {
                    const Res = yield _this10.partsModel.findOne({
                        where: where,
                        // include: [{
                        //     model: this.cellModel,
                        //     attributes: ['BGID'],
                        //     include: [{
                        //         model: this.areaModel,
                        //         attributes: ['parent_ids', 'area_name'],
                        //     }]
                        // }]
                        include: [{
                            model: _this10.partsGroupModel,
                            attributes: ['group_name']

                        }, {
                            model: _this10.areaModel
                        }]
                    });
                    console.log(Res);
                    if (Res) {
                        if (Res.cms_area) {
                            const idArr = Res.cms_area.parent_ids.split(',');
                            console.log(idArr);
                            const areaRes = yield _this10.areaModel.findAll({
                                where: {
                                    id: idArr
                                }
                            });
                            const list = [];
                            idArr.map(function (item2) {
                                areaRes.map(function (item3) {
                                    if (item2 == item3.id) {
                                        list.push(item3.area_name);
                                    }
                                });
                            });
                            list.push(Res.cms_area.area_name);
                            // Res.dataValues.cms_area = null
                            Res.dataValues.address = list;
                        } else {
                            Res.dataValues.address = [];
                        }
                        const imgList = Res.pic_path.split(',');
                        console.log('img', imgList);
                        const newImgList = [];
                        imgList.map(function (item) {
                            if (item) {
                                newImgList.push(serverIP + think.config('imagePath') + '/' + item);
                            }
                        });
                        console.log(newImgList);
                        Res.dataValues.pic_path = newImgList;
                        aj.msg = '查询成功';
                        aj.success = true;
                        aj.result = Res;
                    } else {
                        aj.msg = '当前id不存在';
                        aj.success = false;
                    }
                } catch (error) {
                    aj.msg = error;
                }
            } else {
                aj.msg = '用户名未知';
            }

            return aj;
        })();
    }

    /**
     * 获取损坏的部件
     */
    getBadParts(data) {
        var _this11 = this;

        return _asyncToGenerator(function* () {
            try {
                // let query = {
                //     ObjState: {
                //         $notIn: [data]
                //     }
                // }
                const where = {};
                where.ObjState = {
                    $notIn: data
                };
                const sql = `SELECT * FROM cms_parts WHERE ObjState not in ('完好')`;
                return yield _this11.db.sequelize.query(sql, {
                    type: _this11.db.sequelize.QueryTypes.SELECT
                });
                // return await this.partsModel.findAll({where: {id:{$notIn:[22]}}})
            } catch (error) {
                return _this11.exceptionService.handleError(error);
            }
        })();
    }

    /**
     * 删除部件
     * @param {Object} data
     */
    delParts(data) {
        var _this12 = this;

        return _asyncToGenerator(function* () {
            const Op = _this12.db.Sequelize.Op;
            // const userid = this.defData.userid; //系统用户id,现在写死的
            let where = {};
            if (data.id.length > 0) {
                where = {
                    id: {
                        [Op.in]: data.id
                    }
                };
            }
            try {
                return yield _this12.partsModel.destroy({
                    where: where
                });
            } catch (error) {
                return _this12.exceptionService.handleError(error);
            }
        })();
    }

    /**
     * 获取部件信息及其分类信息
     *
     * @returns
     * @memberof PartsService
     */
    getPartsAndGroupInfo(data) {
        var _this13 = this;

        return _asyncToGenerator(function* () {
            data.start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
            try {
                const Res = yield _this13.partsModel.findAll({
                    // where: where,
                    // order: [
                    // ['id', 'DESC']
                    // ],
                    attributes: ['id', 'ObjID', 'ObjName', 'DeptCode1', 'DeptName1', 'DeptCode2', 'DeptName2', 'DeptCode3', 'DeptName3', 'BGID', 'ObjState', 'ORDate', 'CHDate', 'DataSource', 'Note', 'group_code', 'create_by', 'update_by', 'create_date', 'update_date', 'pic_path', 'area_code', 'address_name', 'baidu_x', 'baidu_y'],
                    limit: parseInt(data.pageSize),
                    offset: parseInt(data.start),
                    // include: [{
                    //     model: this.cellModel,
                    //     attributes: ['BGID'],
                    //     include: [{
                    //         model: this.areaModel,
                    //         attributes: ['parent_ids', 'area_name'],
                    //     }]
                    // }]
                    include: [{
                        model: _this13.partsGroupModel,
                        attributes: ['id', 'parent_id', 'group_name', 'group_pic_path']

                    }]
                    // {
                    //     model: this.areaModel,
                    //     attributes: ['area_name'],
                    // }]

                });

                return Res;
            } catch (error) {
                return _this13.exceptionService.handleError(error);
            }
        })();
    }
    getPartCount() {
        var _this14 = this;

        return _asyncToGenerator(function* () {
            try {
                const Res = yield _this14.partsModel.count();
                return Res;
            } catch (error) {
                return _this14.exceptionService.handleError(error);
            }
        })();
    }

    /**
     * 获取损坏部件信息及其分类信息
     *
     * @returns
     * @memberof PartsService
     */
    getBadPartsAndGroupInfo() {
        var _this15 = this;

        return _asyncToGenerator(function* () {
            const Op = _this15.db.Sequelize.Op;
            const where = {};
            where.ObjState = {
                [Op.ne]: '完好'

            };
            try {
                const Res = yield _this15.partsModel.findAll({
                    where: where,
                    // order: [
                    // ['id', 'DESC']
                    // ],
                    // attributes: ['id', 'baidu_x', 'baidu_y',''],
                    // limit: parseInt(data.pageSize),
                    // offset: parseInt(data.start),
                    // include: [{
                    //     model: this.cellModel,
                    //     attributes: ['BGID'],
                    //     include: [{
                    //         model: this.areaModel,
                    //         attributes: ['parent_ids', 'area_name'],
                    //     }]
                    // }]
                    include: [{
                        model: _this15.partsGroupModel,
                        attributes: ['id', 'parent_id', 'group_name', 'group_pic_path']

                    }]
                    // {
                    //     model: this.areaModel,
                    //     attributes: ['area_name'],
                    // }]

                });

                return Res;
            } catch (error) {
                return _this15.exceptionService.handleError(error);
            }
        })();
    }

    /**
     * 添加BGID
     */
    partsBGID(data) {
        var _this16 = this;

        return _asyncToGenerator(function* () {
            try {
                const query = {
                    BGID: data.BGID
                };
                const where = {
                    id: data.id
                };

                return yield _this16.partsModel.update(data, {
                    where: where
                });
            } catch (error) {
                return _this16.exceptionService.handleError(error);
            }
        })();
    }

    /**
     * 查询字典表数据来源
     */

    dataSource(data) {
        var _this17 = this;

        return _asyncToGenerator(function* () {
            const where = {
                typegroupcode: 'sjly'
            };
            try {
                const type_id = yield _this17.type_group_model.findOne({
                    where: where
                });
                if (type_id) {
                    const query = {
                        typegroupid: type_id.id
                    };
                    return yield _this17.typeModel.findAll({
                        where: query
                    });
                }
            } catch (error) {
                return _this17.exceptionService.handleError(error);
            }
        })();
    }

    /**
     * 更改数据的位数
     * @param {Number} num  需要更改是数字
     * @param {Number} length       需要更为为几位数据
     */
    fix(num, length) {
        return ('' + num).length < length ? (new Array(length + 1).join('0') + num).slice(-length) : '' + num;
    }
}

exports.default = PartsService;